﻿using AutoMapper;
using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.Commands.CottagesCommands
{
    public class CottageCreateHandler : IRequestHandler<CottageCreateCommand, Result>
    {



        private readonly IBaseRepository<Cottages> cottageRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CottageCreateHandler> logger;


        public CottageCreateHandler(IBaseRepository<Cottages> cottageRepository, IMapper mapper, ILogger<CottageCreateHandler> logger)
        {
            this.cottageRepository = cottageRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 添加栋舍信息
        /// </summary>
        /// <param name="request">添加栋舍信息请求对象</param>
        /// <param name="cancellationToken">多线程取消命令</param>
        /// <returns>返回添加栋舍信息响应对象</returns>
        public async Task<Result> Handle(CottageCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result();
                Cottages cottages = mapper.Map<Cottages>(request);

                var w1 = cottageRepository.GetAll().Where(x => x.CottageName == request.CottageName).Count();
                if (w1 > 0)
                {
                    result.Code = -1;
                    result.Messege = "该栋舍名称已存在";
                    return result;
                }

                cottages.CreateTime = DateTime.Now;
                result.Code =  cottageRepository.Add(cottages);
                logger.LogInformation("添加栋舍信息方法调用成功");
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("添加栋舍信息方法调用出错" + ex);
                throw;
            }



        }
    }
}
